// const apiUrl = "http://192.168.0.250:8035"
// const apiUrl = "https://asset.cdrenju.com"
// const apiUrl = "http://127.0.0.1:21022"
// const apiUrl = "http://81.70.79.122:8060"
// const apiUrl = "https://mhapi.mrbytes.xyz"
// const apiUrl = "http://localhost:6450/api"
const apiUrl = "https://mhapi.mrbytes.xyz/api"
import store from '../store/store'
let http = (config) =>{
	
	config.header = store.state.userToken ? {'Authorization': `Bearer ${store.state.userToken}`}: {}
	
	// 处理GET请求的params参数
	let url = apiUrl + config.url;
	if (config.method === 'get' && config.params) {
		const paramStr = Object.keys(config.params)
			.filter(key => config.params[key] !== undefined && config.params[key] !== null)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(config.params[key])}`)
			.join('&');
		if (paramStr) {
			url += (url.includes('?') ? '&' : '?') + paramStr;
		}
	}
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: config.data,
			method: config.method,
			dataType: 'json',
			header: config.header,
			success: (res) => {
				uni.hideLoading()
				if(res.statusCode == 401){
					uni.removeStorageSync('MH_TOKEN')
					// 跳转到MBTI测试页面的phone页面
					uni.reLaunch({
					    url: '/pages/mbit/index?currentPage=phone'
					})
				}else if(res.statusCode == 403){
					//获取获取token
					uni.removeStorageSync('MH_TOKEN')
					// 跳转到MBTI测试页面的phone页面
					uni.reLaunch({
					    url: '/pages/mbit/index?currentPage=phone'
					})
				}
				else{
					resolve(res)
				}
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err)
				uni.showToast({
				    title: '网络异常请稍后再试',
				    icon: 'none'
				})
			}
		})
	})
}

export default {http,apiUrl}